package src.com.syx.queue;

/**
 * @author 邵一鑫
 * @date 2025/6/18 9:51
 */
public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        // 实际有效空间是maxSize-1
        CircleArrayQueue queue = new CircleArrayQueue(5);

        // 入队测试
        queue.enqueue(10);
        queue.enqueue(20);
        queue.enqueue(30);
        queue.enqueue(40);
        queue.enqueue(50); // 队列已满

        // 显示队列
        System.out.println("当前队列内容:");
        queue.list();
        System.out.println("队列大小: " + queue.size());

        // 出队测试
        System.out.println("出队元素: " + queue.dequeue());
        System.out.println("出队元素: " + queue.dequeue());

        // 显示队首元素
        System.out.println("当前队首元素: " + queue.peek());

        // 再次入队
        queue.enqueue(50);
        queue.enqueue(60);

        // 显示队列
        System.out.println("当前队列内容:");
        queue.list();
        System.out.println("队列大小: " + queue.size());
    }
}

class CircleArrayQueue {
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
        this.front = 0; // 指向第一个元素的位置
        this.rear = 0; // 指向下一个插入位置
    }

    // 1. 判断队列是否为空
    public boolean isEmpty() {
        return front == rear;
    }

    // 2. 判断队列是否已满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    // 3. 入队
    public void enqueue(int n) {
        if (isFull()) {
            System.out.println("队列已满，不能加入...");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    // 4. 出队
    public int dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("队列对空，不能取出数据...");
        }
        int value = arr[front];
        front = (front + 1) % maxSize;
        return value;
    }


    // 5. 展示队列所有的数据
    public void list() {
        if (isEmpty()) {
            System.out.println("队列为空...");
            return;
        }
        for (int i = front; i != rear; i = (i + 1) % maxSize) {
            System.out.printf("arr[%d]=%d\n", i, arr[i]);
        }
    }

    // 6. 查看队列头元素（不出队）
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空...");
        }
        return arr[front];
    }

    // 7. 显示队列中有效数据的个数
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }
}
